import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/normal_text_dialog.dart';
import 'package:tender_flutter/http/global.dart';
import 'package:tender_flutter/providers/provider.dart';
import 'package:tender_flutter/providers/user_profile.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/cache.dart';
import 'package:tender_flutter/utils/jpush_utils.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/sputils.dart';
import 'package:tender_flutter/widgets/animation_dialog.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';

class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  /// 是否开启了推送
  bool isOpenPush = true;

  /// 默认需要加载缓存
  bool isLoadCache = true;

  Future<String> cacheSizeFuture;

  /// 退出登录
  showExitLoginDialog({BuildContext context}) async {
    return showAnimationDialog(
        context: context,
        transitionType: TransitionType.fade,
        builder: (context) {
          return NormalTextDialog(
            title: "提示",
            content: "是否确定退出登录？",
          );
        }).then((value) async {
      if (value == AppConstant.DIALOG_ACTION_CONFIRM) {
        Store.value<UserProfileInfo>(context).setUserInfo(null);
        await SPUtils.removeUserInfo();
        await SPUtils.removeToke();
        Global.accessToken = "";
        LRouter.navigatorCtx(context)
            .pushAndRemoveUntil(Routes.mainHomePage, (route) => false);
      }
    });
  }

  @override
  void initState() {
    super.initState();
    cacheSizeFuture = CacheUtils().loadCache();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("设置", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initBody() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [_initList(), _initExitBtn()],
    );
  }

  /// 列表
  Widget _initList() {
    List<Widget> cells = [
      _getNormalCell("用户协议", () {
        LRouter.navigatorCtx(context).push(Routes.protocolPage,
            arguments:
                ProtocolPageArguments(protocolType: AppConstant.PROTOCOL_USER));
      }),
      _getNormalCell("隐私政策", () {
        LRouter.navigatorCtx(context).push(Routes.protocolPage,
            arguments: ProtocolPageArguments(
                protocolType: AppConstant.PROTOCOL_PRIVACY));
      }),
      _getPushCell("推送消息", () {}),
      _getCacheCell()
    ];

    return ListView.separated(
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: cells.length,
      itemBuilder: (BuildContext context, int index) {
        return cells[index];
      },
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          color: ThemeColors.colorType25,
        );
      },
    );
  }

  /// 退出登录按钮
  Widget _initExitBtn() {
    return Container(
      margin: EdgeInsets.only(
          top: ScreenAdapter.height(100),
          left: ScreenAdapter.width(30),
          right: ScreenAdapter.width(30)),
      width: double.infinity,
      height: ScreenAdapter.height(90),
      child: FlatButton(
        color: ThemeColors.colorType6,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(ScreenAdapter.width(14)),
        ),
        child: Text(
          "退出登录",
          style: TextStyle(
              color: ThemeColors.colorWhite, fontSize: ScreenAdapter.sp(30)),
        ),
        onPressed: () {
          showExitLoginDialog(context: context);
        },
      ),
    );
  }

  /// cell
  Widget _getNormalCell(String text, GestureTapCallback callback) {
    return InkWell(
      child: Container(
        height: ScreenAdapter.height(60),
        padding: EdgeInsets.only(
            left: ScreenAdapter.width(30), right: ScreenAdapter.width(30)),
        alignment: Alignment.center,
        child: Row(
          children: <Widget>[
            // SizedBox(height: ScreenAdapter.width(15)),
            Text(text,
                style: TextStyle(
                    color: ThemeColors.colorType1,
                    fontSize: ScreenAdapter.sp(29),
                    fontWeight: FontWeight.w500)),
            Expanded(child: SizedBox()),
            Image.asset(RPath.imgPath + "icon_person_right_arrow.png",
                fit: BoxFit.contain,
                width: ScreenAdapter.width(30),
                height: ScreenAdapter.width(30)),
          ],
        ),
      ),
      onTap: callback,
    );
  }

  /// 推送消息设置cell
  Widget _getPushCell(String text, GestureTapCallback callback) {
    return InkWell(
      child: Container(
        height: ScreenAdapter.height(60),
        padding: EdgeInsets.only(
            left: ScreenAdapter.width(30), right: ScreenAdapter.width(30)),
        alignment: Alignment.center,
        child: Row(
          children: <Widget>[
            // SizedBox(height: ScreenAdapter.width(15)),
            Text(text,
                style: TextStyle(
                    color: ThemeColors.colorType1,
                    fontSize: ScreenAdapter.sp(29),
                    fontWeight: FontWeight.w500)),
            Expanded(child: SizedBox()),
            Switch(
                value: isOpenPush,
                activeColor: ThemeColors.colorType27,
                onChanged: (value) {
                  setState(() {
                    this.isOpenPush = value;
                  });
                  if (isOpenPush) {
                    JPushUtils.resumePush();
                  } else {
                    JPushUtils.stopPush();
                  }
                })
          ],
        ),
      ),
      onTap: callback,
    );
  }

  /// 清除缓存cell
  Widget _getCacheCell() {
    return InkWell(
        onTap: () {
          setState(() {
            cacheSizeFuture = new CacheUtils().clearCache();
          });
        },
        child: Container(
          height: ScreenAdapter.height(60),
          padding: EdgeInsets.only(
              left: ScreenAdapter.width(30), right: ScreenAdapter.width(30)),
          alignment: Alignment.center,
          child: Row(
            children: <Widget>[
              // SizedBox(height: ScreenAdapter.width(15)),
              Text("清除缓存",
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(29),
                      fontWeight: FontWeight.w500)),
              Expanded(child: SizedBox()),

              FutureBuilder(
                  future: cacheSizeFuture,
                  builder:
                      (BuildContext context, AsyncSnapshot<String> snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      return Text(snapshot.data ?? "0B",
                          style: TextStyle(
                              color: ThemeColors.colorType26,
                              fontSize: ScreenAdapter.sp(26)));
                    } else {
                      return SizedBox(
                          width: ScreenAdapter.width(40),
                          height: ScreenAdapter.width(40),
                          child: CircularProgressIndicator(strokeWidth: 1));
                    }
                  })
            ],
          ),
        ));
  }
}
